<?php
namespace app\admin\controller;



use app\admin\model\AdminRole;
use app\admin\model\AdminUser;
use app\admin\model\ShopList;

class AdminController extends BaseController
{

    public function adminList(){

        $role = AdminUser::paginate(10)->each(function ($item){
            $rule = AdminRole::where('id',$item->role)->field('role_name')->find();
            $shop = ShopList::where('id',$item->shop_id)->field('shop_name')->find();
            $item->role =$rule['role_name'];
            $item->shop_id =$shop['shop_name'];
        });
        $this->assign('data',$role);
        return $this->fetch();
    }


    public function adminAdd(){
        $id = (int)input('get.id');
        $data['user'] = AdminUser::get($id);
        $data['role'] = AdminRole::where('status',1)->field('id,role_name')->select()->toArray();
        $data['shop'] = ShopList::where('status',1)->field('id,shop_name')->select()->toArray();
        $this->assign('data',$data);
        return $this->fetch();
    }


    public function adminSave(){
        $id = (int)input('post.id');
        $username = input('post.username');
        $password = input('post.password');
        $role_id = input('post.role');
        $shop_id = input('post.shop_id');
        if (!$id){
            $user = AdminUser::where('username',$username)->find();
            if ($user){
                return json(['code'=>0,'msg'=>'用户名已存在']);
            }
        }
        $data = [
            'username'=>$username,
            'password'=>$password,
            'role'=>$role_id,
            'shop_id'=>$shop_id,
        ];
        if ($id){
            if (!$password){
                unset($data['password']);
            }
            AdminUser::update($data,['id'=>$id]);
        }else{
            AdminUser::create($data);
        }
        return json(['code'=>1,'msg'=>'保存成功']);

    }

    public function adminDel(){
        $id = input('post.id');
        $ret = AdminUser::destroy($id);
        if (!$ret){
            return json(['code'=>0,'msg'=>'删除失败']);
        }
        return json(['code'=>1,'msg'=>'删除成功']);
    }
}